package com.googlecode.gwt.test.plugin.editors;

import org.eclipse.core.resources.IProject;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.jface.text.hyperlink.IHyperlinkDetector;

public class GWTCsvHyperLinkDetector implements IHyperlinkDetector {

	IProject currentProject;
	private KeyWords keywods;

	public GWTCsvHyperLinkDetector(IProject currentProject, KeyWords keyWords) {
		super();
		this.currentProject = currentProject;
		this.keywods = keyWords;
	}

	@Override
	public IHyperlink[] detectHyperlinks(ITextViewer viewer, IRegion region, boolean canShowMultipleHyperlinks) {
		if (region == null || viewer == null)
			return null;

		IDocument document = viewer.getDocument();
		int offset = region.getOffset();

		String urlString = null;
		if (document == null)
			return null;
		IRegion lineInfo;
		String line;
		try {
			lineInfo = document.getLineInformationOfOffset(offset);
			line = document.get(lineInfo.getOffset(), lineInfo.getLength());
		} catch (BadLocationException ex) {
			return null;

		}
		String key = containsCustomKeyWord(line);
		if (key != null) {
			IRegion reg = new Region(lineInfo.getOffset(), key.length());
			return new IHyperlink[] { new CustomKeyWordHyperLink(reg, key, currentProject) };
		}

		if (!line.contains("runmacro;"))
			return null;

		int offsetInLine = offset - lineInfo.getOffset();
		int macroLength = line.length() - "runmacro;".length();
		int macroSeparatorOffset = "runmacro;".length();
		String macroName = line.substring("runmacro;".length(), line.length());
		macroName = macroName.split(";")[0];
		IRegion macroRegion = new Region(lineInfo.getOffset() + macroSeparatorOffset, macroLength);

		return new IHyperlink[] { new MacroHyperLink(macroRegion, macroName, currentProject) };
	}

	private String containsCustomKeyWord(String line) {
		for (String word : keywods.getCustomKeywords()) {
			if (line.contains(word))
				return word;
		}
		return null;
	}

}
